package cn.edu.scau.cmi.liangguan.database.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.scau.cmi.liangguan.database.DAO.StudentDAO;
import cn.edu.scau.cmi.liangguan.database.DAO.TutorDAO;
import cn.edu.scau.cmi.liangguan.database.domain.Student;
import cn.edu.scau.cmi.liangguan.database.domain.Tutor;
import net.sf.json.JSONArray;

/**
 * Servlet implementation class TchServlet
 */
@WebServlet("/TchServlet")
public class TchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TchServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/json;charset=GBK");
		String op = request.getParameter("op");
		StudentDAO studentDAO = new StudentDAO();
		TutorDAO tutorDAO = new TutorDAO();
		PrintWriter out = response.getWriter();
		switch (op) {
		case "1":
			ArrayList<Student> list = studentDAO.getAllStudents();
			out.println(JSONArray.fromObject(list));
			break;
		case "2":
			String sid = request.getParameter("sid");
			String sname = request.getParameter("sname");
			Tutor tutor = new Tutor("1", "peter");
			Student student = new Student(sid,sname);
			if (tutorDAO.selectOrUpdateStudent(student, tutor)) {
				out.println(JSONArray.fromObject(student));	
			}
		break;		
		default:
			break;
		}
	}

}
